package com.soriya.nestlive.common;

import com.soriya.nestlive.util.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@Component
public class ClientInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        List<String> checkUri = List.of(
                "/api/user/info",
                "/api/channel/myChannel"
        );

        String method = request.getMethod();
        String uri = request.getRequestURI();

        String token = request.getHeader("token");
        if (token != null) {
            Long userId = JwtUtil.getMemberIdByToken(token);
            GlobalThreadLocal.put("userId", userId);
        }

        if ("POST".equals(method) || "PUT".equals(method) || "DELETE".equals(method) || checkUri.contains(uri)) {
            if (token == null) return false;
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

}
